<template>
  <div>
    <canvas ref="canvas" width="1330" height="600" class="canvas"></canvas>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import digit from "@/data/data.json";
@Component
export default class Clock extends Vue {
  private cxt: any;
  private digit: number[][][] = digit;
  private radius: number = 8;
  private endTime: number = new Date("2021/2/1").getTime();
  private balls: 

  private mounted() {
    const canvas = this.$refs.canvas as HTMLCanvasElement;
    this.cxt = canvas.getContext("2d");
    this.start(this.getTimeStr());
    setInterval(() => {
      this.start(this.getTimeStr());
    }, 50);
  }

  private created() {}

  private start(str: string) {
    this.cxt.clearRect(0, 0, 1330, 600);
    const strArr: string[] = str.split("");

    let index: number = 0;
    for (let i in strArr) {
      this.renderDigit(index * (this.radius + 1), 20, strArr[i]);
      index += strArr[i] == ":" ? 9 : 15;
    }
  }

  private renderDigit(x: number, y: number, numS: string) {
    this.cxt.fillStyle = "rgb(0,102,153)";
    numS == ":" && (numS = "10");

    const num = Number(numS);
    for (let i: number = 0; i < this.digit[num].length; i++) {
      const arr: number[] = this.digit[num][i];

      for (let j: number = 0; j < arr.length; j++) {
        if (arr[j] == 1) {
          this.cxt.beginPath();
          this.cxt.arc(
            x + j * 2 * (this.radius + 1) + (this.radius + 1),
            y + i * 2 * (this.radius + 1) + (this.radius + 1),
            this.radius,
            0,
            2 * Math.PI
          );
          this.cxt.closePath();
          this.cxt.fill();
        }
      }
    }
  }

  private update() {

  }

  private getTimeStr(): string {
    const nowTime: number = new Date().getTime();
    return this.formaDate(Math.floor((this.endTime - nowTime) / 1000));
  }

  private formaDate(num: number): string {
    const h: number = Math.floor(num / 3600);
    const m: number = Math.floor((num % 3600) / 60);
    const s: number = num % 60;
    const sh: string = h >= 10 ? h.toString() : "0" + h;
    const sm: string = m >= 10 ? m.toString() : "0" + m;
    const ss: string = s >= 10 ? s.toString() : "0" + s;
    return `${sh}:${sm}:${ss}`;
  }
}
</script>

<style scoped lang="scss">
.canvas {
  border: 1px solid #333;
  transform: translate(-50%, -50%);
  position: fixed;
  top: 50%;
  left: 50%;
}
</style>
